/*
 * Fittsen: map mouse button events on screen corners to commands.
 *
 * Based on fittstool taken from https://github.com/jeanCarloMachado/fittstool
 *
 * Copyright (C) 2009  Yasen Atanasov <yasen.atanasov@gmail.com>
 * Copyright (C) 2019  Lucas Skoldqvist <frusen@gungre.ch>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 */

#include <xcb/xcb.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "ini.h"

#define str_defined(str) ( (strlen(str) > 0) ? 1 : 0 )
#define get_cmd(win,cmd) win_opt[win].commands[cmd]
#define N_GROUPS 8
#define N_ACTIONS 9

enum eScreenCorners {
    TopLeft, TopCentre, TopRight, Right, BottomRight, BottomCentre, BottomLeft,
    Left
};

enum eMouseButtons {
    LeftButton, MiddleButton, RightButton, WheelUp, WheelDown, WheelUpOnce,
    WheelDownOnce, Enter, Leave
};

enum eXCBButtonIndexes {
    LEFT_BUTTON=1, MIDDLE_BUTTON, RIGHT_BUTTON, WHEEL_UP_BUTTON,
    WHEEL_DOWN_BUTTON
};

struct str_window_options {
    char enabled;
    int x;
    int y;
    int h;
    int w;
    char commands[N_ACTIONS][200]; // TODO: ARG_MAX
    xcb_window_t xcb_window; // pointer to the newly created window
    time_t last_time_up;     // last time a wheel up has been made
    time_t last_time_down;   // last time a wheel down has been made
} win_opt[N_GROUPS];

char draw_areas = 0;

void
server_create_windows(xcb_connection_t *connection, xcb_screen_t *screen)
{
    uint32_t values[2];
    values[0] = 1; // XCB_CW_OVERRIDE_REDIRECT: inform WM not to tamper with window
    values[1] = XCB_EVENT_MASK_BUTTON_PRESS |
        XCB_EVENT_MASK_ENTER_WINDOW |
        XCB_EVENT_MASK_LEAVE_WINDOW;

    for (int i=0; i<N_GROUPS; i++) {
        // Skip unenabled windows
        if (win_opt[i].enabled == 0)
            continue;

        win_opt[i].xcb_window = xcb_generate_id (connection);

        xcb_create_window(connection, 0, win_opt[i].xcb_window,
            screen->root, win_opt[i].x, win_opt[i].y,
            win_opt[i].w, win_opt[i].h, 0,
            XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual,
            XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK, values);

        // Draw windows with white pixels if enabled
        if (draw_areas == 1)
            xcb_change_window_attributes(connection, win_opt[i].xcb_window,
                XCB_CW_BACK_PIXEL, &screen->white_pixel);

        xcb_map_window(connection, win_opt[i].xcb_window);
    }

    xcb_flush(connection);
}

int
server_find_window(xcb_window_t win)
{
    for (int i=0; i<N_GROUPS; i++)
        if (win_opt[i].xcb_window == win)
            return i;
    return -1;
}

int
can_execute(const int corner, int direction)
{
    time_t current_time;
    time_t *last_exec;
    long int diff;

    if (!direction)
        last_exec = &win_opt[corner].last_time_up;
    else
        last_exec = &win_opt[corner].last_time_down;

    time(&current_time);
    diff = (long int) current_time - (long int) *last_exec;

    if (!last_exec || (diff > 2)) {
        *last_exec = current_time;
        return 1;
    }

    return 0;
}

void
server_event_loop (xcb_connection_t *connection)
{
    xcb_generic_event_t *event;
    xcb_button_press_event_t *bp;
    xcb_enter_notify_event_t *enter;
    xcb_leave_notify_event_t *leave;

    while ((event = xcb_wait_for_event (connection))) {
        switch (event->response_type & ~0x80) {
        case XCB_BUTTON_PRESS:
            bp = (xcb_button_press_event_t *)event;
            int cur_win = server_find_window(bp->event);

            switch (bp->detail) {
            case LEFT_BUTTON:
                if (str_defined(get_cmd(cur_win, LeftButton)))
                    system(get_cmd(cur_win, LeftButton));
                break;

            case MIDDLE_BUTTON:
                if (str_defined(get_cmd(cur_win,MiddleButton)))
                    system(get_cmd(cur_win,MiddleButton));
                break;

            case RIGHT_BUTTON:
                if (str_defined(get_cmd(cur_win,RightButton)))
                    system(get_cmd(cur_win,RightButton));
                break;

            case WHEEL_UP_BUTTON:
                if (str_defined(get_cmd(cur_win,WheelUp)))
                    system(get_cmd(cur_win,WheelUp));
                if (str_defined(get_cmd(cur_win,WheelUpOnce)) &&
                  can_execute(cur_win, 0) )
                    system(get_cmd(cur_win,WheelUpOnce));
                break;

            case WHEEL_DOWN_BUTTON:
                if (str_defined(get_cmd(cur_win,WheelDown)))
                    system(get_cmd(cur_win,WheelDown));
                if (str_defined(get_cmd(cur_win,WheelDownOnce)) &&
                  can_execute(cur_win, 1) )
                    system(get_cmd(cur_win,WheelDownOnce));
                break;
            }
            break;

        case XCB_ENTER_NOTIFY:
            enter = (xcb_enter_notify_event_t *)event;
            cur_win = server_find_window(enter->event);
            if (str_defined(get_cmd(cur_win,Enter)))
                system(get_cmd(cur_win,Enter));
            break;

        case XCB_LEAVE_NOTIFY:
            leave = (xcb_leave_notify_event_t *)event;
            cur_win = server_find_window(leave->event);
            if (str_defined(get_cmd(cur_win,Leave)))
                system(get_cmd(cur_win,Leave));
            break;

        default:
            break;
        }

        free (event);
    }
}

void
init_options (const int scr_w, const int scr_h)
{
    for (int i=0; i<N_GROUPS; i++) {
        win_opt[i].enabled = 0;
        win_opt[i].last_time_down = (time_t)0;
        win_opt[i].last_time_up = (time_t)0;
    }

    win_opt[TopLeft].w = 5;
    win_opt[TopLeft].h = 5;
    win_opt[TopLeft].x = 0;
    win_opt[TopLeft].y = 0;

    win_opt[TopCentre].w = scr_w*0.4;
    win_opt[TopCentre].h = 2;
    win_opt[TopCentre].x = (scr_w - win_opt[TopCentre].w)/2;
    win_opt[TopCentre].y = 0;

    win_opt[TopRight].w = 6;
    win_opt[TopRight].h = 5;
    win_opt[TopRight].x = scr_w-5;
    win_opt[TopRight].y = 0;

    win_opt[Right].w = 3;
    win_opt[Right].h = scr_h*0.4;
    win_opt[Right].x = scr_w-2;
    win_opt[Right].y = (scr_h - win_opt[Right].h)/2;

    win_opt[BottomRight].w = 6;
    win_opt[BottomRight].h = 6;
    win_opt[BottomRight].x = scr_w-5;
    win_opt[BottomRight].y = scr_h-5;

    win_opt[BottomCentre].w = scr_w*0.4;
    win_opt[BottomCentre].h = 2;
    win_opt[BottomCentre].x = (scr_w - win_opt[BottomCentre].w)/2;
    win_opt[BottomCentre].y = scr_h-2;

    win_opt[BottomLeft].w = 5;
    win_opt[BottomLeft].h = 5;
    win_opt[BottomLeft].x = 0;
    win_opt[BottomLeft].y = scr_h-5;

    win_opt[Left].w = 2;
    win_opt[Left].h = scr_h*0.4;
    win_opt[Left].x = 0;
    win_opt[Left].y = (scr_h - win_opt[Left].h)/2;
}

int
get_section(const char *section)
{
    if (strcmp(section, "TopLeft") == 0)
        return 0;
    else if (strcmp(section, "TopCentre") == 0)
        return 1;
    else if (strcmp(section, "TopRight") == 0)
        return 2;
    else if (strcmp(section, "Right") == 0)
        return 3;
    else if (strcmp(section, "BottomRight") == 0)
        return 4;
    else if (strcmp(section, "BottomCentre") == 0)
        return 5;
    else if (strcmp(section, "BottomLeft") == 0)
        return 6;
    else if (strcmp(section, "Left") == 0)
        return 7;
    else
        return -1;
}

int
get_name(const char *name)
{
    if (strcmp(name, "LeftButton") == 0)
        return 0;
    else if (strcmp(name, "MiddleButton") == 0)
        return 1;
    else if (strcmp(name, "RightButton") == 0)
        return 2;
    else if (strcmp(name, "WheelUp") == 0)
        return 3;
    else if (strcmp(name, "WheelDown") == 0)
        return 4;
    else if (strcmp(name, "WheelUpOnce") == 0)
        return 5;
    else if (strcmp(name, "WheelDownOnce") == 0)
        return 6;
    else if (strcmp(name, "Enter") == 0)
        return 7;
    else if (strcmp(name, "Leave") == 0)
        return 8;
    else
        return -1;
}

static int
handler(void *user, const char *section, const char *name, const char *value)
{
    if (strcmp(section, "Options") == 0) {
        if (strcmp(name, "DrawAreas") == 0)
            draw_areas = 1;
        return 1;
    }

    int s = get_section(section);
    if (s == -1) return 0; // unknown section
    int n = get_name(name);
    if (n == -1) return 0; // unknown name

    win_opt[s].enabled = 1;

    // TODO: bounds check
    strcpy(win_opt[s].commands[n], value);
    strcat(win_opt[s].commands[n], " &");
    printf("%s %s : %s\n", section, name, win_opt[s].commands[n]);

    return 1;
}

int
config_read()
{
    char *home = getenv("HOME");

    if (home == NULL) {
        fprintf(stderr, "Variable HOME is not in the current environment\n");
        return -1;
    }

    char *post = "/.fittsen.cfg";
    char *fp = calloc(strlen(home)+strlen(post)+1, 1);

    if (fp == NULL) {
        fprintf(stderr, "Failure to allocate\n");
        return -1;
    }

    // TODO: bounds check
    strcat(fp, home);
    strcat(fp, post);

    if (ini_parse(fp, handler, NULL) < 0) {
        fprintf(stderr, "Cannot load ~/.fittsen.cfg\n");
        free(fp);
        return -1;
    }
    free(fp);

    return 0;
}

int
main(int argc, char *argv[])
{
    xcb_connection_t *conn = xcb_connect(NULL, NULL);

    if (xcb_connection_has_error(conn) > 0) {
        fprintf(stderr, "Cannot connect to X\n");
        return 1;
    }

    xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;

    if (screen == NULL) {
        fprintf(stderr, "Cannot get screen\n");
        xcb_disconnect(conn);
        return 1;
    }

    init_options(screen->width_in_pixels, screen->height_in_pixels);

    if (config_read() == -1) {
        return 1;
    }

    server_create_windows(conn, screen);
    server_event_loop(conn);

    xcb_disconnect(conn);

    return 0;
}
